# vim: set ft=sh :

# Real-time ripgrep with fzf

local file_type=""
local base_dir="." # Default to current directory

while [[ $# -gt 0 ]]; do
    case $1 in
        --file-type | -f)
            shift
            file_type="$1"
            shift
            ;;

        --dir | -d)
            shift
            base_dir="$1"
            shift
            ;;
    esac
done

local rg_opts="--trim --color=always --line-number --smart-case"

if [[ -n "$file_type" ]]; then
    rg_opts="$rg_opts --type=$file_type"
fi

local search_cmd="reload:rg $rg_opts {q} $base_dir || :"
local highlight_cmd="bat --color=always --pager=never {1} --highlight-line={2}"
local edit_cmd="become:$EDITOR {1} +{2} -c \"exec 'normal zz'\""

fzf --disabled \
    --ansi \
    --reverse \
    --delimiter ':' \
    --bind "start:$search_cmd" \
    --bind "change:$search_cmd" \
    --bind "enter:$edit_cmd" \
    --bind 'ctrl-j:preview-down' \
    --bind 'ctrl-k:preview-up' \
    --preview "$highlight_cmd" \
    --preview-window 'nohidden,+{2}+3/5,~3'
